package com.skyline.courier.net.provider.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

import com.skyline.courier.net.Heartbeat;
import com.skyline.courier.net.Serializer;

public class NettySerializeHandler extends ChannelOutboundHandlerAdapter {
	private Serializer serializer;
	
	public NettySerializeHandler(Serializer serializer) {
		this.serializer = serializer;
	}
	
	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		Object originalMessage = msg;
		Object encodedMessage = originalMessage;

		if (!(originalMessage instanceof Heartbeat)) {
			encodedMessage = serializer.serialize(originalMessage);
		} else {
			encodedMessage = Heartbeat.BYTES;
		}

		super.write(ctx, encodedMessage, promise);
		
	}
}
